package com.xinlong.shop.framework.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinlong.shop.framework.cache.ICache;
import com.xinlong.shop.framework.core.entity.SysMenu;
import com.xinlong.shop.framework.core.mapper.SysMenuMapper;
import com.xinlong.shop.framework.core.model.SysMenuDTO;
import com.xinlong.shop.framework.service.ISysMenuService;
import com.xinlong.shop.framework.util.FrameworkCacheEnum;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 22:08 2022/5/31
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    private final SysMenuMapper sysMenuMapper;

    private final ICache cache;

    public SysMenuServiceImpl(SysMenuMapper sysMenuMapper, ICache cache) {
        this.sysMenuMapper = sysMenuMapper;
        this.cache = cache;
    }

    @Override
    public List<SysMenu> findAllMenus() {


        List<SysMenu> menus  = (List<SysMenu>) cache.get(FrameworkCacheEnum.ALL_MENU.toString());

        if (menus == null) {
            menus = sysMenuMapper.findAllMenus();
            cache.put(FrameworkCacheEnum.ALL_MENU.toString(),menus);
        }
        return menus;
    }

    @Override
    public List<SysMenuDTO> findMenusTree() {

        List<SysMenuDTO> allMenus = this.sysMenuMapper.findMenusForDTO();
        // 树结构菜单列表
        List<SysMenuDTO> treeMenus = new ArrayList<>();

        for (SysMenuDTO menu : allMenus) {
            // 1级
            if(menu.getPid().intValue() == 0) {
                List<SysMenuDTO> children = this.getChildren(allMenus, menu.getId());
                menu.setChildren(children);
                treeMenus.add(menu);
            }
        }

        return treeMenus;
    }

    @Override
    public void add(SysMenu sysMenu) {
        this.save(sysMenu);
        cache.delete(FrameworkCacheEnum.ALL_MENU.toString());
    }

    @Override
    public void update(SysMenu sysMenu) {
        this.updateById(sysMenu);
        cache.delete(FrameworkCacheEnum.ALL_MENU.toString());
    }

    /**
     * 获得指定子菜单DTO 集合
     * @param menus
     * @param pid
     * @return
     */
    private List<SysMenuDTO> getChildren(List<SysMenuDTO> menus, Integer pid) {
        List<SysMenuDTO> children = new ArrayList<>();
        for(SysMenuDTO menu : menus) {
            if (menu.getPid() == pid) {

                // 递归获取子菜单
                menu.setChildren(this.getChildren(menus, menu.getId()));
                children.add(menu);
            }
        }
        return children;
    }

}
